import pandas as pd
import numpy as np
from tkinter.filedialog import *
import matplotlib.pyplot as plt
from scipy import stats


def readcsv(filename='', filelist=list()):
    # read csv by pandas
    # askopen
    if filename == '':
        filename = askopenfile()

        # obtain the pathname
        # read all file names
        (path, temp) = os.path.split(filename.name)
        files = os.listdir(path)
        files.sort()
        s = []
        for file_ in files:
            if not os.path.isdir(path + file_):  # if it is not a directory
                f_name = str(file_)
                s.append(path + '/' + f_name)
        filelist = [i for i in s if (i[-4:] == ".csv")]
    # jump the askopen and use the input filename
    csv_data = pd.read_csv(filename, header=None)  # no headers
    #  read columns to list
    colname = csv_data.columns
    coldata = {}
    for i in colname:
        coldata[i] = csv_data[i].values

    return coldata, filelist
    # type of coldata[i] is numpy.array
    # type of colname is dict


class signal:
    def __init__(self, sdata, freq):
        self.sdata = sdata
        self.freq = freq

    def mapsignal(self):
        totalfig = len(self.sdata)
        f, axarr = plt.subplots(totalfig, sharex=True, sharey=False)
        axarr[0].set_title('ALL singal')
        for i in range(0, totalfig):
            self.sdata[i] = self.sdata[i].astype(np.float128)  # !!! here only float128 !!! not float, not float64 ...
            axarr[i].plot(np.arange(0, len(self.sdata[i])/self.freq, 1/self.freq), self.sdata[i], color='r')
            axarr[i].set_xlabel('time(s)')
            axarr[i].set_ylabel('voltage(V)')

    def parameters(self):
        totalfig = len(self.sdata)
        data_mean = []
        data_sigma = []
        data_skew = []
        data_kurtosis = []
        for i in range(0, totalfig):
            sdata_float128 = self.sdata[i].astype(np.float128)  # !!! here only float128 !!! not float, not float64 ...
            sdata_float64 = sdata_float128.astype(np.float64)  # first to float128, then to float64, otherwise error ...
            # ! should run mapsignal fisrt to convert the str to float128 !
            # ! status deal with float64 ! errors with float128
            data_mean.append(np.mean(sdata_float64))
            data_sigma.append(np.std(sdata_float64))
            data_skew.append(stats.skew(sdata_float64))
            data_kurtosis.append(stats.kurtosis(sdata_float64))
        return data_mean, data_sigma, data_skew, data_kurtosis

    def parameters_Nth(self, N):
        sdata_float128 = self.sdata[N].astype(np.float128)  # !!! here only float128 !!! not float, not float64 ...
        sdata_float64 = sdata_float128.astype(np.float64)  # first to float128, then to float64, otherwise error ...
        # ! should run mapsignal fisrt to convert the str to float128 !
        # ! status deal with float64 ! errors with float128
        data_RMS = np.sqrt(sdata_float64**2)
        data_sigma = np.std(sdata_float64)
        data_skew = stats.skew(sdata_float64)
        data_kurtosis = stats.kurtosis(sdata_float64)
        return data_RMS, data_sigma, data_skew, data_kurtosis


# SamplingF = 2*10**9  # sampling frequency
# Sdata, Pathname = readcsv('/home/yxy/Rawdata/Test1_LaserEnergy/pf-0-100uj-64v.csv')
# Sdata, Pathname = readcsv()
# S = signal(Sdata, SamplingF)  # select file and read csv
# print(Pathname)
# S.mapsignal()
#
#
# S_mean, S_sigma, S_skew, S_kurtosis = S.parameters()
# print(S_mean)
# print(S_kurtosis)
# print(S_sigma)
# print(S_kurtosis)
